package models

type Stock struct {
	Model
	Num         int    `json:"num"`
	StorageId   int    `json:"storage_id"`
	StorageName string `json:"storage_name"`
	ProductId   int    `json:"product_id"`
	ProductName string `json:"product_name"`
	ProductSpec string `json:"product_spec"`
}

func AddStock(data map[string]interface{}) bool {
	err := db.Create(&Stock{
		Num:         data["num"].(int),
		StorageId:   data["storage_id"].(int),
		StorageName: data["storage_name"].(string),
		ProductId:   data["product_id"].(int),
		ProductName: data["product_name"].(string),
		ProductSpec: data["product_spec"].(string),
	}).Error
	if err != nil {
		return false
	}
	return true
}

func ExistStock(storageId int, productId int) bool {
	var stock Stock
	db.Model(&Stock{}).Where("storage_id=? and product_id=?", storageId, productId).Find(&stock)

	if stock.ID > 0 {
		return true
	}
	return false
}

func ExistStockById(id int) bool {
	var stock Stock
	err := db.Model(&Stock{}).Where("id=?", id).Find(&stock).Error
	if err != nil {
		return false
	}
	if stock.ID > 0 {
		return true
	}
	return false
}

func EditStockNum(id int, num int) bool {
	err := db.Model(&Stock{}).Where("id=?", id).Update("num", num).Error
	if err != nil {
		return false
	}
	return true
}

func GetStock(id int) (*Stock, error) {
	var stock Stock
	err := db.Where("id=?", id).First(&stock).Error
	if err != nil {
		return nil, err
	}
	return &stock, nil
}

func GetStockList(pageNum int, pageSize int, maps map[string]interface{}) ([]*Stock, error) {
	var stocks []*Stock
	err := db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&stocks).Error
	if err != nil {
		return nil, err
	}
	return stocks, nil
}

func GetStockTotal(maps map[string]interface{}) (int, error) {
	var count int
	err := db.Model(&Stock{}).Where(maps).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

/**
添加库存
*/
func IncrementStockNum(storageId int, productId int, num int) bool {
	var stock Stock
	db.Where("storage_id=? and product_id=?", storageId, productId).Find(&stock)

	if stock.ID < 0 {
		//创建一条数据
		var data map[string]interface{}
		product, _ := GetProductById(productId)
		storage, _ := GetStorageById(storageId)
		data["storage_id"] = storageId
		data["storage_name"] = storage.Name
		data["product_id"] = productId
		data["product_name"] = product.Name
		data["product_spec"] = product.Spec
		data["num"] = num
		AddStock(data)
		return true
	}

	nums := stock.Num + num
	err := db.Where("storage_id=? and product_id=?", storageId, productId).Update("num", nums).Error
	if err != nil {
		return false
	}
	return true
}

func DecrementStockNum(storageId int, productId int, num int) bool {
	var stock Stock
	db.Where("storage_id=? and product_id=?", storageId, productId).Find(&stock)
	nums := stock.Num - num
	if nums < 0 {
		return false
	}
	err := db.Where("storage_id=? and product_id=?", storageId, productId).Update("num", nums).Error
	if err != nil {
		return false
	}
	return true
}
